<!--
 * @Author: wangming
 * @Date: 2020-09-09 14:04:55
 * @LastEditors: wangming
 * @LastEditTime: 2021-08-17 15:02:35
 * @Description:添加类别按钮
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="600px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建" : "编辑" }}{{ formData.type | pageType }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="120px">
      <el-form-item
        label="页面名称"
        prop="name"
        :rules="[
          { required: true, message: '页面名称不能为空', trigger: 'change' },
        ]"
      >
        <el-input
          v-model="formData.name"
          style="width: 400px"
          placeholder="请输入页面名称"
          :maxlength="64"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item
        label="关联模型"
        prop="modelId"
        :rules="[
          { required: true, message: '请选择关联模型', trigger: 'change' },
        ]"
      >
        <tree-select
          style="width: 400px"
          v-if="isNew"
          v-model="formData.modelId"
          :loading="modelLoading"
          filterable
          :fieldMap="{
            value: 'id',
            label: 'name',
            disabled: 'disabled',
          }"
          :filterNodeMethod="filterNodeMethod"
          :treeData="modelList"
        />

        <el-input
          v-else
          disabled
          v-model="formData.modelName"
          style="width: 400px"
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="formData.type === 'FORM'"
        label="表单创建方式"
        prop="createWay"
        :rules="[
          { required: true, message: '请选择表单创建方式', trigger: 'change' },
        ]"
      >
        <el-radio-group :disabled="!isNew" v-model="formData.createWay">
          <el-radio
            v-for="(value, key) in FORM_CREATE_TYPE_ENUM"
            :key="key"
            :label="key"
            >{{ value }}</el-radio
          >
        </el-radio-group>
      </el-form-item>

      <el-form-item label="页面描述">
        <el-input
          type="textarea"
          v-model="formData.description"
          style="width: 400px"
          placeholder="请输入页面描述"
          :maxlength="200"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="showVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { cloneDeep, debounce } from "lodash";
import { FORM_CREATE_TYPE_ENUM } from "@/utils/enum";
import { filterNodeMethod } from "@/utils/treeSelectFormat";

import { getHmmodelfolderListTree } from '@/apis/paas/HmModelFolderController.js'
import { postHmpage,putHmpage } from '@/apis/paas/HmPageController.js'
import { treeToArray } from '@/utils/util'

const defaultaFormData = {
  createWay: Object.keys(FORM_CREATE_TYPE_ENUM)[0],
};

export default {
  data() {
    this.loadModelList = debounce(this.loadModelList, 500);
    return {
      showVisible: false,
      filterNodeMethod,
      FORM_CREATE_TYPE_ENUM,
      modelList: [],
      modelLoading: false,
      formData: {},
      callback: () => {},
      validator: (rule, value, callback) => {
        callback();
      },
    };
  },

  computed: {
    isNew() {
      return !this.formData.id;
    },
    listData () {
      return treeToArray(this.modelList)
    },
  },

  methods: {
    addForm(record = {}) {
      this.formData = {
        ...record,
        ...defaultaFormData,
      };
      return this.showModel();
    },

    editForm(record) {
      this.formData = { ...record };
      return this.showModel();
    },

    showModel() {
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      this.loadModelList();
      return {
        then: (callback) => {
          if (typeof callback === "function") {
            this.callback = callback;
          }
        },
      };
    },

    loadModelList() {
      this.modelLoading = true;
      getHmmodelfolderListTree()
        .then((res) => {
          res.forEach((node) => {
            node.type = "folder";
          });
          this.modelList = this.createModelTreeNode(res);
        })
        .finally(() => {
          this.modelLoading = false;
        });
    },

    async submit() {
      try {
        await this.$refs.form.validate();
        const { id, name, modelId, type, createWay, description, folderId } =
          this.formData;
        let modelCode;
        if(modelId){
          modelCode = this.listData.find((item) => item.id === modelId).code
        }
        let params = {};
        let request = null;
        if (this.isNew) {
          params = { name, modelId, type, createWay, description, folderId };
          request = postHmpage;
        } else {
          params = { id, name, description };
          request = putHmpage;
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        request(params).then((id) => {
          this.showVisible = false;
          this.callback({ createWay, modelId, name, id, modelCode });
        });
      } catch (error) {}
    },
    createModelTreeNode(tree) {
      return cloneDeep(tree).map((node) => {
        node.disabled = node.type === "folder";
        if (node.modelResults) {
          node.id = "folder" + node.id;
          node.children = node.modelResults || [];
          node.children.forEach((item) => {
            item._id = item.id;
            item.name = `${item.name}(${item.code})`;
          });
        }
        return node;
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
